/**
 * 什么是死锁
 * 哲学家就餐
 *
 * @author fireway
 * @since 2019年 03月 01日 星期五 06:54:10 CST
 */
package concurrency;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DeadlockingDiningPhilosophers {
    public static void main(String[] args) {
        int ponder = 5;
        if(args.length > 0) {
            ponder = Integer.parseInt(args[0]);
            System.out.println("ponder = " + ponder);
        }

        int size = 5;
        if(args.length > 1) {
            size = Integer.parseInt(args[1]);
            System.out.println("size = " + size);
        }

        ExecutorService exec = Executors.newCachedThreadPool();
        Chopstick[] sticks = new Chopstick[size];
        for(int i = 0; i < size; i++) {
            sticks[i] = new Chopstick();
        }

        for(int i = 0; i < size; i++) {
            exec.execute(new Philosopher(sticks[i], sticks[(i+1) % size], i, ponder));
        }

        try {
            if (args.length == 3 && args[2].equals("timeout"))
                TimeUnit.SECONDS.sleep(5);
            else {
                System.out.println("Press 'Enter' to quit");
                System.in.read();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        exec.shutdownNow();
    }
}
